package com.example.myapp.APP;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.NotesData;
import com.example.myapp.Model.User;
import com.example.myapp.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class Bianqin extends AppCompatActivity {

  private   ImageView bianqianback;
  private   Button yincang;
  private   Button     bianqianclear;
  private   Button tianjia;

  private   Button bianqiansave;
  private TextView tvmantitle;
  private   EditText editconter;
  private   ListView lsitbianqian;
  private  boolean VisibilityKey=true;
  private  List<NotesData> noticeList = new ArrayList<>();
  private  String objId="";
  private ShapeLoadingDialog shapeLoadingDialog;
  private int addkey=0;
    private  boolean isUpdata=false;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {

                    Adapter adapter = new Adapter(Bianqin.this,noticeList);//NewAdapterDAO为自定义适配器
                    lsitbianqian.setAdapter(adapter);
                    break;
                }
                case 2:{

                    BmobQuery<NotesData> query = new BmobQuery<NotesData>();
                    User user = BmobUser.getCurrentUser(User.class);//查询自己
                    //friend是User表中的字段，用来存储所有关注的用户
                    query.addWhereEqualTo("author",user.getObjectId());
                    //包含作者信息
                    query.include("user,author");
                    query.order("-updatedAt");
                    query.findObjects(new FindListener<NotesData>() {
                        @Override
                        public void done(List<NotesData> object, BmobException e) {
                            if (e == null) {
                                noticeList=object;
                                Adapter adapter = new Adapter(Bianqin.this,noticeList);//NewAdapterDAO为自定义适配器
                                lsitbianqian.setAdapter(adapter);
                                Log.w("aaaa", "成功！"+object.size());

                            } else {
                                Log.e("aaaa","失败"+ e.getMessage());

                            }
                        }
                    });
                }  break;
            }
        }
    };
    public void onBackPressed() {
        //此处写退向后台的处理
        finish();
    }//手机返回键
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.bianqian);
        Bmob.initialize(this, "33854715fa739da69a015d5ab944d101");
        bianqianback=findViewById(R.id.bianqianback);
        editconter=findViewById(R.id.editconter);
        tvmantitle=findViewById(R.id.tvmantitle);
        lsitbianqian=findViewById(R.id.lsitbianqian);
        yincang=findViewById(R.id.yincang);
        bianqiansave=findViewById(R.id.bianqiansave);
        bianqianclear=findViewById(R.id.bianqianclear);
        tianjia=findViewById(R.id.tianjia);


            querynotes();

        TextWatcher textWatcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                bianqiansave.setVisibility(View.VISIBLE);

            }
        };
        editconter.addTextChangedListener(textWatcher);
        bianqiansave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(tvmantitle.getText().toString().trim().length()>0) {
                        if(!isUpdata) {//如果不是更新就保存
                            NotesData notesData = new NotesData();
                            notesData.setTitle(tvmantitle.getText().toString());
                            notesData.setContent(editconter.getText().toString());
                            notesData.setAuthor(BmobUser.getCurrentUser(User.class));
                            notesData.save(new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    if (e == null) {
                                        objId = s;
                                        Collections.reverse(noticeList);//倒序
                                        noticeList.add(notesData);
                                        Collections.reverse(noticeList);//倒序
                                       // Toast.makeText(Bianqin.this, "保存成功", Toast.LENGTH_SHORT).show();
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                        addkey = 1;
                                        Log.w("aaaa", "创建便签成功" + s);
                                    } else {
                                        Log.w("aaaa", "创建便签失败");
                                    }
                                }
                            });
                        }else {//是更新
                            NotesData upData =new NotesData();
                            upData.setContent(editconter.getText().toString());
                            upData.setTitle(tvmantitle.getText().toString());
                            upData.update(objId, new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                Log.w("aaaa", "更改成功" );
                                Collections.reverse(noticeList);//倒序
                                noticeList.add(upData);
                                Collections.reverse(noticeList);//倒序
                             //   Toast.makeText(Bianqin.this, "保存成功", Toast.LENGTH_SHORT).show();
                                Message message = new Message();
                                message.what = 2;
                                handler.sendMessage(message);
                                addkey = 1;

                              //  Toast.makeText(Bianqin.this, "更新成功", Toast.LENGTH_SHORT).show();
                                isUpdata=false;
                            } else {
                                Log.w("aaaa", "更改数据失败：" + e.getMessage());
                            }
                        }
                    });
                        }
                    }
                else {
                    Toast.makeText(Bianqin.this,"请先填写标题",Toast.LENGTH_SHORT).show();
                }
                }
            });
        bianqianback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              finish();
            }
        });
        bianqianclear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(Bianqin.this);
                builder.setIcon(R.drawable.jinggao);
                builder.setTitle("您确定删除吗？");
                builder.setNeutralButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        clearNotes(objId);
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    }
                });
                builder.setNegativeButton("取消",null);
                builder.show();

            }
        });

        yincang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (VisibilityKey){
                lsitbianqian.setVisibility(View.GONE);
                    VisibilityKey=false;
                }else {
                    lsitbianqian.setVisibility(View.VISIBLE);
                    VisibilityKey=true;
                }
            }
        });
        tianjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addkey==0){
                    AlertDialog.Builder builder=new AlertDialog.Builder(Bianqin.this);
                    builder.setIcon(R.drawable.jinggao);
                    builder.setTitle("当前便签未保存是否继续？");
                    builder.setNeutralButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            tvmantitle.setText("");
                            editconter.setText("");
                        }
                    });
                    builder.setNegativeButton("取消",null);
                    builder.show();
                }else {
                    tvmantitle.setText("");
                    editconter.setText("");
                    addkey=0;
                    bianqianclear.setVisibility(View.INVISIBLE);
                }


            }
        });
    }
    private void querynotes(){
        openLoading();
        BmobQuery<NotesData> query = new BmobQuery<NotesData>();
        User user = BmobUser.getCurrentUser(User.class);//查询自己
        //friend是User表中的字段，用来存储所有关注的用户
        query.addWhereEqualTo("author",user.getObjectId());
        //包含作者信息
        query.include("user,author");
        query.order("-updatedAt");
        query.findObjects(new FindListener<NotesData>() {
            @Override
            public void done(List<NotesData> object, BmobException e) {
                if (e == null) {
                    noticeList=object;
                    Message message = new Message();
                    message.what = 1;
                    // message.obj = s;//得到是本地图片地址，将地址已消息的方式发送给线程
                    handler.sendMessage(message);
                closeLoading();
                    Log.w("aaaa", "查询记账表成功！"+object.size());

                } else {
                    Log.e("aaaa","失败"+ e.getMessage());

                }
            }
        });

    }









    private class Adapter extends BaseAdapter {
        private Context context;

        private  List<NotesData> noticeList = new ArrayList<>();
        private LayoutInflater mInflater;
        public Adapter(Context context,List<NotesData> noticeList) {
            this.context = context;
            this.noticeList = noticeList;

            mInflater = LayoutInflater.from(context);//初始化
        }
        @Override
        public boolean areAllItemsEnabled() {
            return super.areAllItemsEnabled();
        }
        @Override
        public int getCount() {
            return noticeList.size();
        }

        @Override
        public Object getItem(int i) {
            return noticeList.get(i);
        }
        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = mInflater.inflate(R.layout.bianqianlist, null);
            TextView tvtitleman = view.findViewById(R.id.tvtitleman);
            tvtitleman.setText(noticeList.get(i).getTitle());
            tvtitleman.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tvmantitle.setText(noticeList.get(i).getTitle());
                    editconter.setText(noticeList.get(i).getContent());
                    objId=noticeList.get(i).getObjectId();
                    isUpdata=true;
                    addkey=1;
                    bianqianclear.setVisibility(View.VISIBLE);
                }
            });


            return view;
        }
    }


    private void clearNotes( String notesobjId){
        openLoading();
        NotesData notesData = new NotesData();
        notesData.setObjectId(notesobjId);
        notesData.delete(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if(e==null){
                    Log.w("aaaab:","删除成功"+notesData.getUpdatedAt());
                    closeLoading();
                }else{
                    Log.w("aaaab","删除失败：" + e.getMessage());
                }
            }
        });
    }


    //网络加载
    private  void openLoading(){
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(Bianqin.this)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }
    //关闭网络加载
    private  void closeLoading(){
        shapeLoadingDialog.dismiss();
    }



}
